// 多选题
import React, { useState, useRef, useEffect, useContext } from "react";

import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Dimensions,
  Image,
  Modal,
  ActivityIndicator,
  Alert,
  Platform,
  StatusBar,
  TouchableWithoutFeedback,
} from "react-native";

import ImageViewer from "react-native-image-zoom-viewer";
import VideoPlayer from "expo-video-player";
import { Audio } from "expo-av";
import * as MediaLibrary from "expo-media-library";
import * as FileSystem from "expo-file-system";
import Icon from "@expo/vector-icons/Entypo";
import { Feather } from "@expo/vector-icons";
import { MaterialIcons } from "@expo/vector-icons";
import { ResizeMode } from "expo-av";
import { Tabs, MaterialTabBar } from "react-native-collapsible-tab-view";
import AsyncStorage from "@react-native-async-storage/async-storage";
import InterviewContext from "../../context/interview/InterviewContext";
import LoadingBar from "../../components/InterView/LoadingBar";
import AudioListItemNodelete from "../../components/InterView/AudioListItemNodelete";
import { play, pause, resume, playNext } from "../../utils/audioController";
import { fileWeb } from "../../api/query";

const { width: DEVICE_WIDTH, height: DEVICE_HEIGHT } = Dimensions.get("window");

const Loading = () => {
  return (
    <View>
      <ActivityIndicator animating={true} size={"large"} />
    </View>
  );
};

const ShowFileData = ({ filedata }) => {
  console.log("filedata---", filedata);

  const [inFullscreen, setInFullsreen] = useState(false);
  //放大图片
  const [magnifypVisible, setMagnifypVisible] = useState(false);
  const [index, setIndex] = useState(0);
  const [imagesUrl, setimagesUrl] = useState([]);
  //保存图片/视频权限
  const [hasMediaLibraryPermission, setHasMediaLibraryPermission] = useState();
  //编辑删除Modal可见性
  const [isVisible, setIsVisible] = useState(false);
  //控制编辑删除Modal偏移量 距离上方多少
  const [topOffset, setTopOffset] = useState(0);
  //加载
  const [isLoading, setIsLoading] = useState(false);
  const refVideo = useRef(null);
  let positionMark = useRef();

  const [currentAudio, setCurrentAudio] = useState({});
  const [currentAudioIndex, setCurrentAudioIndex] = useState(null);
  const [soundObj, setSoundObj] = useState(null);
  const [playbackObj, setPlaybackObj] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [role, setRole] = useState();

  useEffect(() => {
    let isMounted = true;

    const getPermission = async () => {
      const permission = await MediaLibrary.getPermissionsAsync();
      if (permission.granted && isMounted) {
        setHasMediaLibraryPermission(true);
      }
      if (!permission.granted && permission.canAskAgain) {
        const { status, canAskAgain } =
          await MediaLibrary.requestPermissionsAsync();
        if (status === "granted" && isMounted) {
          setHasMediaLibraryPermission(true);
        }
        if (status === "denied" && canAskAgain) {
          permissionAllert();
        }
        if (status === "denied" && !canAskAgain) {
          alert("未授权访问媒体库的权限，请在设置中进行修改");
        }
      }
      if (!permission.canAskAgain && !permission.granted) {
        alert("未授权访问媒体库的权限，请在设置中进行修改");
      }
    };
    getPermission();
    getRole();

    return () => {
      isMounted = false;
    };
  }, []);

  const getRole = async () => {
    const role = await AsyncStorage.getItem("role");
    setRole(role);
  };

  const permissionAllert = () => {
    Alert.alert("权限请求", "本App需要读取系统媒体库的权限", [
      {
        text: "允许",
        onPress: () => getPermission(),
      },
      {
        text: "不允许",
        onPress: () => alert("未授权访问媒体库的权限，请在设置中进行修改"),
      },
    ]);
  };

  const saveImage = async (url) => {
    if (url.substring(0, 7) != "file://") {
      const localpicture = await FileSystem.downloadAsync(
        url,
        FileSystem.documentDirectory + "image.jpg"
      );
      if (localpicture.status != 200) {
        alert("下载失败！");
      } else {
        url = localpicture.uri;
      }
    }
    if (hasMediaLibraryPermission) {
      try {
        MediaLibrary.saveToLibraryAsync(url).then(() => {
          alert("已保存到系统相册");
        });
      } catch (error) {
        alert("保存时出错了！");
      }
    } else {
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const saveVideo = async (url) => {
    if (url.substring(0, 7) != "file://") {
      const localvideo = await FileSystem.downloadAsync(
        url,
        FileSystem.documentDirectory + "video.mp4"
      );
      if (localvideo.status != 200) {
        alert("下载失败！");
      } else {
        url = localvideo.uri;
      }
    }
    if (hasMediaLibraryPermission) {
      try {
        MediaLibrary.saveToLibraryAsync(url).then(() => {
          alert("已保存到系统相册");
        });
      } catch (error) {
        alert("保存时出错了！");
      }
    } else {
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const saveVideoAlert = (url) => {
    Alert.alert("提示", "要保存这个视频吗?", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          saveVideo(url);
        },
      },
    ]);
  };

  //处理录音点击事件
  const handleAudioPress = async (audio) => {
    const index = filedata.soundfile.indexOf(audio);
    // playing audio for the first time.
    if (soundObj === null) {
      const playbackObj = new Audio.Sound();
      const status = await play(playbackObj, fileWeb + "/" + audio.filePath);
      setCurrentAudio(audio);
      setCurrentAudioIndex(index);
      setIsPlaying(true);
      setPlaybackObj(playbackObj);
      setSoundObj(status);

      playbackObj.setOnPlaybackStatusUpdate((playbackStatus) => {
        if (playbackStatus.didJustFinish) {
          setCurrentAudio({});
          setCurrentAudioIndex(null);
          setIsPlaying(false);
          setPlaybackObj(null);
          setSoundObj(null);
        }
      });
    } else {
      // pause audio
      if (
        soundObj.isLoaded &&
        soundObj.isPlaying &&
        index === currentAudioIndex
      ) {
        const status = await pause(playbackObj);
        setSoundObj(status);
        setIsPlaying(false);
      }
      // resume audio
      if (
        soundObj.isLoaded &&
        !soundObj.isPlaying &&
        index === currentAudioIndex
      ) {
        const status = await resume(playbackObj);
        setSoundObj(status);
        setIsPlaying(true);
      }
      // select another audio
      if (soundObj.isLoaded && index !== currentAudioIndex) {
        const status = await playNext(
          playbackObj,
          fileWeb + "/" + audio.filePath
        );
        setCurrentAudio(audio);
        setSoundObj(status);
        setIsPlaying(true);
        setCurrentAudioIndex(index);
      }
    }
  };

  return (
    <View style={styles.borderView}>
      {/* 图片 */}
      <View>
        <View
          style={{
            alignItems: "center",
          }}
        >
          <Text style={{ fontSize: 17, fontWeight: "bold" }}>图片资料</Text>
        </View>
        {/* <View style={styles.imageList}> */}
        {filedata.image.length > 0 ? (
          <View style={styles.imageList}>
            {filedata.image.map((image, index) => {
              return (
                <View key={index}>
                  {/* 图片列表，点击放大 */}
                  <TouchableOpacity
                    onPress={() => {
                      var newimageList = filedata.image.map((item) => ({
                        url: fileWeb + "/" + item.filePath,
                        props: {},
                      }));
                      setimagesUrl(newimageList);
                      setIndex(index);
                      setMagnifypVisible(true);
                    }}
                  >
                    <Image
                      source={{ uri: fileWeb + "/" + image.filePath }}
                      style={[
                        index % 3 == 2
                          ? styles.lascolsingleimage
                          : styles.singleimage,
                        { resizeMode: "cover" },
                      ]}
                    />
                  </TouchableOpacity>
                </View>
              );
            })}
            {/* 放大图片 */}
            <Modal visible={magnifypVisible} animationType={"fade"}>
              <ImageViewer
                imageUrls={imagesUrl}
                menuContext={{ saveToLocal: "保存图片", cancel: "取消" }}
                loadingRender={Loading}
                index={index}
                onClick={() => {
                  setMagnifypVisible(false);
                }}
                onSave={() => {
                  saveImage(imagesUrl[index].url);
                }}
              />
            </Modal>
          </View>
        ) : (
          <View
            style={{ alignItems: "center", marginTop: 10, marginBottom: 20 }}
          >
            <Text style={{ color: "#ddd" }}>暂无图片文件</Text>
          </View>
        )}
        {/* </View> */}
      </View>
      {/* 录音 */}
      <View>
        <View
          style={{
            alignItems: "center",
          }}
        >
          <Text style={{ fontSize: 17, fontWeight: "bold" }}>录音资料</Text>
        </View>
        {filedata.soundfile.length > 0 ? (
          <View>
            <View style={styles.interviewaudio}>
              {filedata.soundfile.map((item, index) => {
                return (
                  <AudioListItemNodelete
                    key={index}
                    audioTitle={"录音" + (index + 1)}
                    isPlaying={isPlaying}
                    activeListItem={currentAudioIndex === index}
                    onAudioPress={() => handleAudioPress(item)}
                  />
                );
              })}
            </View>
          </View>
        ) : (
          <View
            style={{ alignItems: "center", marginTop: 10, marginBottom: 20 }}
          >
            <Text style={{ color: "#ddd" }}>暂无录音文件</Text>
          </View>
        )}
      </View>
      {/* 视频 */}
      <View>
        <View
          style={{
            alignItems: "center",
          }}
        >
          <Text style={{ fontSize: 17, fontWeight: "bold" }}>视频资料</Text>
        </View>
        {filedata.video.length > 0 ? (
          <View>
            <View style={styles.videoList}>
              {filedata.video.map((video, index) => {
                return (
                  <View key={index}>
                    {/* 下载视频的按钮 */}
                    <TouchableOpacity
                      onPress={() => {
                        saveVideoAlert(fileWeb + "/" + video.filePath);
                      }}
                      style={styles.downloadvideo}
                    >
                      <Feather
                        name="download"
                        size={19}
                        color="#ffffff"
                        style={{ zIndex: 10 }}
                      />
                    </TouchableOpacity>
                    {/* 视频列表 */}
                    <View style={{ marginBottom: 15 }}>
                      <VideoPlayer
                        videoProps={{
                          shouldPlay: false,
                          resizeMode: ResizeMode.CONTAIN,
                          source: {
                            uri: fileWeb + "/" + video.filePath,
                          },
                          ref: refVideo,
                        }}
                        style={{
                          height: inFullscreen
                            ? DEVICE_WIDTH
                            : (DEVICE_WIDTH * 3) / 5,
                          width: inFullscreen
                            ? DEVICE_HEIGHT
                            : (DEVICE_WIDTH * 4) / 5,
                          videoBackgroundColor: "#000000",
                        }}
                      />
                    </View>
                  </View>
                );
              })}
            </View>
          </View>
        ) : (
          <View
            style={{ alignItems: "center", marginTop: 10, marginBottom: 20 }}
          >
            <Text style={{ color: "#ddd" }}>暂无视频文件</Text>
          </View>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  borderView: {
    paddingTop: 9,
    paddingLeft: 15,
    paddingRight: 15,
    paddingBottom: 10,
    // justifyContent: "center",
    // backgroundColor: "#eee",
    // height: "100%",
  },
  topContainer: {
    height: DEVICE_HEIGHT / 2,
    width: "100%",
    borderBottomLeftRadius: 50,
    borderBottomRightRadius: 50,
    backgroundColor: "#A80108",
    flexDirection: "column",
    justifyContent: "space-between",
    alignContent: "center",
  },
  head: {
    flexDirection: "row",
    justifyContent: "space-between",
    width: "100%",
    marginTop: 40,
    paddingHorizontal: 20,
  },
  fileName: {
    fontSize: 23,
    fontWeight: "bold",
    color: "#FDCE95",
    alignSelf: "center",
  },
  fileType: {
    fontSize: 14,
    color: "#FFF5E8",
    alignSelf: "center",
    marginTop: 6,
  },
  rowStyle: {
    width: (13 * DEVICE_WIDTH) / 15,
    flexDirection: "row",
    justifyContent: "space-between",
    alignContent: "center",
    marginTop: 13,
  },
  firstrowStyle: {
    width: (13 * DEVICE_WIDTH) / 15,
    flexDirection: "row",
    justifyContent: "space-between",
    alignContent: "center",
  },
  rowItem: {
    borderRadius: 20,
    paddingVertical: 8,
  },
  tagText: {
    fontSize: 14,
    color: "#FEDDB6",
    alignSelf: "center",
    marginTop: 1,
  },
  tagCount: {
    fontWeight: "bold",
    fontSize: 13,
    color: "#FFF5E8",
    alignSelf: "center",
  },
  //访谈图片位置信息
  imageList: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "flex-start",
    alignContent: "center",
    paddingHorizontal: (DEVICE_WIDTH * 3) / 40,
    paddingTop: 20,
  },
  singleimage: {
    backgroundColor: "#eee",

    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    marginRight: DEVICE_WIDTH / 20,
    marginBottom: DEVICE_WIDTH / 20,
    position: "relative",
    resizeMode: "contain",
  },
  lascolsingleimage: {
    backgroundColor: "#eee",
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    marginBottom: DEVICE_WIDTH / 20,
    position: "relative",
    resizeMode: "contain",
  },
  videoList: {
    flexDirection: "column",
    justifyContent: "flex-start",
    alignItems: "center",
    paddingVertical: 20,
  },
  downloadvideo: {
    position: "absolute",
    zIndex: 5,
    left: 0,
    top: 0,
    backgroundColor: "#595959",
    opacity: 0.7,
    padding: 2,
  },
  ModalBackground: {
    backgroundColor: "#d5d5d5",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: DEVICE_WIDTH,
    height: DEVICE_HEIGHT,
  },
  bubblePosition: {
    position: "absolute",
    right: 17,
    zIndex: 10,
  },
  bubbleModal: {
    position: "relative",
  },
  rectangle: {
    backgroundColor: "#fff",
    paddingTop: 25,
    paddingLeft: 15,
    borderRadius: 15,
    borderTopRightRadius: 10,
    paddingRight: 20,
    zIndex: 5,
    paddingRight: 30,
  },
  rectangleText: {
    fontSize: 17,
    marginLeft: 10,
    textAlign: "center",
    textAlignVertical: "center",
    fontWeight: "bold",
    color: "#2b2b2b",
  },
  rectangleItem: {
    // backgroundColor: "yellow",
    flexDirection: "row",
    marginBottom: 25,
    zIndex: 10,
    // padding: 10,
  },
  triangle: {
    width: 0,
    height: 0,
    borderBottomWidth: 5,
    borderBottomColor: "#fff",
    borderLeftWidth: 5,
    borderLeftColor: "transparent",
    borderRightWidth: 5,
    borderRightColor: "transparent",
    position: "absolute",
    right: 10,
    top: -5,
    zIndex: 5,
  },
  interviewaudio: {
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    paddingTop: 20,
  },
});

export default ShowFileData;
